from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from .core.config import settings
from .routers import movies, analytics

def create_application() -> FastAPI:
    app = FastAPI(
        title=settings.PROJECT_NAME,
        openapi_url=f"{settings.API_V1_STR}/openapi.json",
        docs_url=f"{settings.API_V1_STR}/docs",
        redoc_url=f"{settings.API_V1_STR}/redoc",
    )

    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.BACKEND_CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 确保静态文件目录存在
    settings.STATIC_DIR.mkdir(parents=True, exist_ok=True)
    settings.IMAGES_DIR.mkdir(parents=True, exist_ok=True)

    # 挂载静态文件目录
    app.mount("/static", StaticFiles(directory=str(settings.STATIC_DIR)), name="static")

    # 注册路由
    app.include_router(movies.router)
    app.include_router(analytics.router)

    @app.get("/")
    async def root():
        return {
            "message": "Welcome to Movie Recommendation API",
            "docs_url": f"{settings.API_V1_STR}/docs"
        }

    return app

app = create_application()